﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Threading.Tasks;

namespace FotoLab.DataLayer.JpegStorage
{
    public class AzureJpegStorage : IJpegStorage
    {

        private CloudBlobContainer container;
        private static int MaximumBlobSize = 5000000; // 5 MiB

        public AzureJpegStorage(string connectionString, string containerName)
        {
            var account = CloudStorageAccount.Parse(connectionString);
            container = account.CreateCloudBlobClient().GetContainerReference(containerName);
        }

        public Stream Retrieve(string fotoId)
        {
            var stream = new MemoryStream();

            bool hasMoreData = true;
            for (int chunk = 1; hasMoreData; chunk++)
            {
                var blob = container.GetBlockBlobReference(fotoId + ".jpg.chunk" + chunk);
                if (blob.Exists())
                {
                    var positionBefore = stream.Position;
                    blob.DownloadToStream(stream);
                    var readBytes = stream.Position - positionBefore;

                    if (readBytes < MaximumBlobSize)
                    {
                        // Er bestaan geen chunks meer, want deze
                        // is kleiner dan de maximum size
                        hasMoreData = false;
                    }
                }
                else
                {
                    hasMoreData = false;
                }
            }

            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

        public void Store(string fotoId, Stream jpegStream)
        {
            bool hasMoreData = true;

            for (int chunk = 1; hasMoreData; chunk++)
            {
                byte[] buffer = new byte[MaximumBlobSize];
                int readBytes = jpegStream.Read(buffer, 0, (int) MaximumBlobSize);

                if (readBytes > 0)
                { 
                    var blob = container.GetBlockBlobReference(fotoId + ".jpg.chunk" + chunk);
                    blob.UploadFromByteArray(buffer, 0, readBytes);
                }
                else
                {
                    hasMoreData = false;
                }
            }
        }

        public void DeleteAll()
        {
            Parallel.ForEach(
                container.ListBlobs(), 
                blob => ((CloudBlob) blob).Delete()
            );
        }

    }
}